import * as THREE from 'three'
import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls'
import { TWEEN } from 'three/examples/jsm/libs/tween.module.min';
import $ from 'jquery';
import { CSS3DRenderer } from 'three/examples/jsm/renderers/css3drenderer';
import { computed } from 'vue';
import { dataListStore } from '../../stores/dataList';
import { loaderModel,fbxLoaderModel} from "./threeLoadOneModel"
import { ElMessage } from 'element-plus'


let element = undefined;
let width = undefined;
let height = undefined;
let scene = undefined;
let camera = undefined;
let renderer = undefined;
let controls = undefined;
let ambientLight = undefined;
let label3DRender = undefined;
let modelLcGroup = undefined;
let labelGroup = undefined;
let css3dLabelGroup = undefined;
let css3dLabelXQGroup = undefined;
const store = dataListStore();
let data = store.dataList;
let className = store.classNames;
const stateName = store.stateName; 
let directLight = undefined;

export function initThree(id, data) { 
    THREE.Cache.enabled = true;
    element = document.getElementById(id);
    width = element.clientWidth;
    height = element.clientHeight;
    createGroup();
    //创建场景
    createScene();
    //创建摄像机
    createCamera();
    createLight();
    //创建渲染器
    createRenderer();
    createControls();
    css3DRenderer(width, height, element);
    loaderModel(data,scene,modelLcGroup,labelGroup,css3dLabelGroup,css3dLabelXQGroup);
    //fbxLoaderModel(data,scene,modelLcGroup,labelGroup,css3dLabelGroup,css3dLabelXQGroup);
    window.alertInfo = alertInfo;
}
function createGroup() { 
    modelLcGroup = new THREE.Group();
    modelLcGroup.name = "modelLcGroup";
    labelGroup = new THREE.Group();
    labelGroup.name = "labelGroup";
    css3dLabelGroup = new THREE.Group();
    css3dLabelGroup.name = "css3dLabelGroup";
    css3dLabelXQGroup = new THREE.Group();
    css3dLabelXQGroup.name = "css3dLabelXQGroup";
}
function createScene() {
    scene = new THREE.Scene();
    //scene.background = new THREE.Color(0, 0, 0);
    scene.add(modelLcGroup);
    scene.add(labelGroup);
    scene.add(css3dLabelGroup);
    scene.add(css3dLabelXQGroup);
}
function createCamera() {
    camera = new THREE.PerspectiveCamera(45,width/height,1,800000);
    camera.position.z = 100;
}
export function updateLabelColor(key) {
    let data = store.dataList[key];
    let wz = "除尘器A侧右室";
    if (data.hopper.indexOf('A1-') != -1 || data.hopper.indexOf('A2-') != -1) {
        wz = '除尘器A侧右室'
    } else if (data.hopper.indexOf('A3-') != -1 || data.hopper.indexOf('A4-') != -1) {
        wz = '除尘器A侧左室'
    }else if (data.hopper.indexOf('B1-') != -1 || data.hopper.indexOf('B2-') != -1) {
        wz = '除尘器B侧右室'
    }else if (data.hopper.indexOf('B3-') != -1 || data.hopper.indexOf('B4-') != -1) {
        wz = '除尘器B侧左室'
    }

    $("#oneLabelTitles,#oneLabelXq .top,#oneLabelXq .bottom,#oneLabelXq .top .center .labelNrHw,#oneLabelXq .top .center .labelNrZt,#oneLabelXq .top .center .labelNrHz,#oneLabelXq .top .center .labelNrHzai,#oneLabelXq .top .center .labelNrZhl").removeClass('normal').removeClass('green').removeClass('yellow').removeClass('red').removeClass('fault').removeClass('green').addClass(className[data.state]);
    $("#oneLabelTitles span,#oneLabelXq .top .center .labelNrMc").html(key);
    //$("#oneLabelXq .top,#oneLabelXq .bottom").removeClass('normal').removeClass('yellow').removeClass('red').removeClass('fault').addClass(className[data.state]);
    $(".labelXq_realtime .top .title span").html(wz);
    $("#oneLabelXq .top .center .labelNrHw").html(data.height.toFixed(2) + '米');
    $("#oneLabelXq .top .center .labelNrZt").html(stateName[data.state]);
    $("#oneLabelXq .top .center .labelNrHzai .in-press").css({width: `${data.load_rate.toFixed(4)*100 > 100 ? 100 : data.load_rate.toFixed(4)*100}%`});
    $("#oneLabelXq .top .flex-press-one span").removeClass('normal').removeClass('yellow').removeClass('red').removeClass('fault').removeClass('green').addClass(className[data.state]).text((data.load_rate.toFixed(4)*100).toFixed(2)+'%');

    getBl("A1-1", data.height,data);
    
    // let data = store.dataList;
    // for( let key in data ){
    //     let item = data[key];
    //     $(`.${key}`).removeClass('normal').removeClass('yellow').removeClass('red').removeClass('fault').addClass(className[item.state])
    //     getBl( key, item.height );
    // }
}

function getBl(name, height, data) {
    height = height ? height : 0;
    if( name ){
        let needHd = store.modellcNameList[name];
        if( needHd ){
            let hdName = needHd.modelName;
            let mesh = modelLcGroup.getObjectByName( hdName );
            if( mesh ){
                let h = Number( mesh.userData.size.height );
                let chH = height / 6.4 * h;
				if( chH >= h ){
					chH = h; 
				}
                // mesh.material.clippingPlanes[0].constant = mesh.material.userData.initH + chH;
				
                let w = Number( mesh.userData.size.width );
                let d = Number( mesh.userData.size.depth );
                let s = chH / h;
                let sx = ( ( w - 4.65 ) * s + 4.65 ) / w;
                let sz = ((d - 4.65) * s + 4.65) / d;
                
                mesh.scale.set( sx * mesh.userData.scale.x, s * mesh.userData.scale.y, sz * mesh.userData.scale.z );
                mesh.position.y = mesh.userData.position.y - h * (1 - s) * 0.15
                upadteMateRial(mesh, data.state);
            }
        }
    }
}


// function getBl(name, height, data) {
//     height = height ? height / 38.46 : 0;
//     if( name ){
//         let needHd = store.modellcNameList[name];
//         if( needHd ){
//             let hdName = needHd.modelName;
//             let mesh = modelLcGroup.getObjectByName( hdName );
//             if( mesh ){
//                 debugger
//                 let h = Number( mesh.userData.size.height );
//                 let hScale = Number( height ) / h;
//                 // 11.5 cha
//                 // boxMesh.position.set(mesh.position.x, mesh.position.y + 11.5 + height, mesh.position.z);
//                 // mesh.scale.set( hScale * mesh.userData.scale.x, hScale * mesh.userData.scale.y, hScale * mesh.userData.scale.z );
//                 // mesh.position.y = mesh.userData.position.y - h * (1 - hScale) * 15;
//                 upadteMateRial(mesh, data.state);
                
//             }
//         }
//     }
// }

let textureNormal = new THREE.TextureLoader().load('static/colorNormal.jpg');
let textureYellow = new THREE.TextureLoader().load('static/colorYellow.jpg');
let textureGreen = new THREE.TextureLoader().load('static/colorGreen.jpg');
let textureRed = new THREE.TextureLoader().load('static/colorRed.jpg');
let textureFault = new THREE.TextureLoader().load('static/colorFault.jpg');

function upadteMateRial(mesh, data) {
    let map = textureNormal.clone();
    let emissive = 0x00ffff;
    if (data == 0) {
       emissive = 0x00ffff; 
       map = textureNormal.clone();
    } else if (data == 1) {
        emissive = 0xFFFF00; 
        map = textureGreen.clone(); 
    } else if (data == 2) {
        emissive = 0xFF6633;
        map = textureYellow.clone();
    } else if (data == 3 || data == 4) {
        emissive = 0xFF0000;
        map = textureRed.clone();
    }else if (data == 5) {
        emissive = 0xC0C0C0;
        map = textureFault.clone();
    }
	mesh.material = mesh.material.clone(true);
    mesh.material.color = new THREE.Color(emissive);
    mesh.material.emissive = new THREE.Color(emissive);
    mesh.material.emissiveIntensity = 0.5;
    mesh.material.flatShading = true;
    mesh.material.metalness = 1.0;
    mesh.material.roughness = 0.0;

	
    // mesh.material.color = emissive;
    // mesh.material.emissive = emissive;
    // mesh.material.map((item,index) => {
    //     if (item.name == 'gray_01') {
    //         mesh.material[index] = new THREE.MeshBasicMaterial({
    //             map: map,
    //             color: emissive,
    //             emissive:emissive,
    //             name: 'gray_01',
    //             emissiveMap:map
    //         })
    //     }
    // })
    // console.log(mesh.material);
    //console.log(mesh);
}

function createLight() {
    ambientLight = new THREE.AmbientLight(0xffffff,1);
    scene.add(ambientLight);
    directLight = new THREE.DirectionalLight( 0xffffff, 1 );
    scene.add(directLight);
}
function createRenderer() {
    renderer = new THREE.WebGLRenderer({
        precision:'highp',
        alpha:true,
        antialias:true
    });
    renderer.shadowMap.enabled  = true;
    renderer.autoClear = true;
    renderer.outputEncoding = THREE.sRGBEncoding;//調整色彩飽和度
    // renderer.physicallyCorrectLights = false;
    // renderer.toneMappingExposure = 0.1;
    renderer.setSize(width,height);
    // renderer.localClippingEnabled = true;
    element.appendChild(renderer.domElement);
    // element.addEventListener('pointermove', mouseMove, false);
    // element.addEventListener('pointerup', mouseUp, false);
    // element.addEventListener('pointerdown', mouseDown, false);
}
function createControls() {
    controls = new OrbitControls(camera, renderer.domElement);
    controls.object.position.set(-93.57139641543768,85.56698464673241,-163.0330632240862);
    controls.target.set(4.767249118521343,63.29157270300425,32.783519734316634);
	controls.enabled = false;
}
function css3DRenderer(width, height, element) {
    label3DRender = new CSS3DRenderer();
    label3DRender.setSize(width, height);
    label3DRender.domElement.style.position = 'absolute';
    label3DRender.domElement.style.top = '0px';
    label3DRender.domElement.style.pointerEvents = 'none';
    element.appendChild(label3DRender.domElement);
}
// function getDeg() {
//     if (css3dLabelGroup && css3dLabelGroup.children.length > 0) {
//         const bodyDirection = camera.getWorldDirection(new THREE.Vector3());
//         css3dLabelGroup.children.map((item,index) => {
//             item.rotation.y = -Math.atan2(bodyDirection.x, bodyDirection.z) + Math.PI * 2;
//             css3dLabelXQGroup.children[index].rotation.y = -Math.atan2(bodyDirection.x, bodyDirection.z) + Math.PI * 2;
//         })
        
//     }
// }
export function render() {
    
    if (css3dLabelXQGroup.children[0]) {
        const bodyDirection = camera.getWorldDirection(new THREE.Vector3());
        css3dLabelXQGroup.children[0].rotation.y = -Math.atan2(bodyDirection.x, bodyDirection.z) + Math.PI * 2;
    }
    controls.update();
    directLight.position.x = camera.position.x - 10;
    directLight.position.y = camera.position.y - 10;
    directLight.position.z = camera.position.z - 10;
    if ( label3DRender ) {
        label3DRender.render(scene, camera);
    }
    renderer.setSize(width,height);
    renderer.render(scene,camera);
    requestAnimationFrame(render);
}
export function alertInfo( a, b) {
    ElMessage({
        message: `实时灰重:${a.toFixed(2)}t/设计极限载灰量:${b.toFixed(2)}t`,
        type: 'warning',
      })
      return;
}